$(document).ready(function(){
    laydate.render({
      elem: '#startTime'
      ,type: 'datetime'
    });

    laydate.render({
      elem: '#endTime'
      ,type: 'datetime'
    });
    validateRule();
    setfile();
//    setfilecontract();
     selectAddOption("status","proCategoryType","");

     $(".slainput").on("blur",addTime(this));
});


$('#test1').on('click',function(){
    $('input[type=file]').get(0).click();
});
function initBase(){
	selectAddOption("status","ci_state","");
	$.ajax({
		type : "POST",
		headers:PRIVATE_HEADERS,
		url : API_SERVER_URL + "cim/ciAudit/getById",
		data : "withLists=false&id="+$("#ciIdInput").val(),
		async : true,
		error : function(request) {
			parent.layer.alert("Connection error");
		},
		success : function(data) {
			$("#firstForm").json2form({data:data});
			initCategory();
		}
	});
}

function removeLine(obj){
      layer.confirm('确定要删除选中的记录？', {
      		btn : [ '确定', '取消' ]
      	}, function(index) {
      	//alert($(obj).parents("tr").html());
      	   var trObj=$(obj).parents("tr");
      	   var trParent=$(trObj).parents("tbody");
            $(trObj).remove();
            var indexTr=1;
            var str="";

            $(trParent).children("tr").each(function(){
                $(this).children().first().html('SLA'+indexTr);
               indexTr++;
            });
            layer.close(index);
      	})
}
//计算和
function myParseInt(num){
//console.log(num)
     if(num==''){
         num=0;
       }else{
          num=parseInt(num);
       }

       return num;
}

function addTime(obj){
   var  aTime=$(obj).val();
   var aName=$(obj).attr("name");
//   console.log(aName);
   aName=aName.substring(0,aName.lastIndexOf("["));

   var one=myParseInt($("[name='"+aName+"[0].kpiValue"+"']").val());

   var two=myParseInt($("[name='"+aName+"[1].kpiValue"+"']").val());

   var three=myParseInt($("[name='"+aName+"[2].kpiValue"+"']").val());

   var chu=one+two+three;

   $("[name='"+aName+"[3].kpiValue"+"']").val(parseInt(one)+parseInt(two)+parseInt(three));
   //console.log($("[name='"+aName+"']").val());
   //console.log(aName);
}
function number(){
    var count = $('#opp').val();
    var trObj ='';
    var serviceName=['服务响应', '服务到场','服务解决','服务中断'];
    for(var i=0;i<parseInt(count);i++){
    trObj = trObj + '<tr><td class="center"><input type="hidden" name="slaDoList['+i+'].slaName" value="SLA'+(i+1)+'" type="display:block; margin-left:5px">SLA'+(i+1)+'</input></td>';
    for(var j=0;j<4;j++){
    if(j<3){
        trObj = trObj + '<td><input  name="slaDoList['+i+'].slaKpiDTOList['+j+'].kpiName" value="'+serviceName[j]+'"  class="hidden" type="text"/><input  onblur="addTime(this)" name="slaDoList['+i+'].slaKpiDTOList['+j+'].kpiValue" class="slainput"  type="number"/></td>';
    }
      if(j == 3){
        trObj = trObj + '<td><input  name="slaDoList['+i+'].slaKpiDTOList['+j+'].kpiName" value="'+serviceName[j]+'"  class="hidden" type="text"/><input  name="slaDoList['+i+'].slaKpiDTOList['+j+'].kpiValue" class="slainput"   disabled="disabled" type="number"/></td>';
        }
       }x
     trObj=trObj+'<td type="width:100%"><div type="text-align:center"><button type="button" class="btn1 btn  btn-primary" onclick="removeLine(this);"><i class="fa-plus hidden" aria-hidden="true"></i>删除</button></div></td></tr>';
    }
    $("#tab1 tbody").html('');
    $("#tab1 tbody").append(trObj);

    $('input[class=slainput]').on('input',function(){
        addTime(this)
    });
}
function saveFirst() {
	$.ajax({
		cache : true,
		type : "POST",
		headers:PRIVATE_HEADERS,
		url : API_SERVER_URL + "smm/project/save",
		data : $('#signupForm').serialize(),// 你的formid
		async : false,
		error : function(request) {
			parent.layer.alert("Connection error");
		},
		success : function(data) {
			if (data.code == 0) {
				parent.layer.alert("保存成功，请进行下一步操作。");
				$("#auditID").val(data.id);
                $("#moduleInput").val('smm');
                $("#typeInput").val('image');
                $("#serviceIdImput").val();
                parent.reLoad();
               var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
				parent.layer.close(index);
			} else {
				parent.layer.alert(data.msg)
			}
		}
	});
}
function validateRule() {
	$("#signupForm").validate({
		submitHandler:function(form){
            saveFirst();
        }
	})
}
function setfile(){
    $("#uploader").html('<div id="thelist" class="uploader-list"></div>'+
    			    '<div class="btns">'+
    			     	'<div id="picker">上传附件</div>'+
    			    '</div>');
        var uploader = WebUploader.create({
            swf: '../../../static/js/plugins/webuploader/Uploader.swf',
            headers: PRIVATE_HEADERS,
            server: window.API_SERVER_URL + 'ftp/uploadFiles/smm/project',
            pick: '#picker',
            resize: false,
            auto: true
        });
        // 当有文件被添加进队列的时候，添加到页面预览
        uploader.on( 'fileQueued', function( file ) {
            $('#thelist').append( '<div id="' + file.id + '" class="item">' +
                '<h4 class="info">' + file.name + '</h4>' +
                '<p class="state">等待上传...</p>' +
                '</div>' );
        });
        // 文件上传过程中创建进度条实时显示。
        uploader.on( 'uploadProgress', function( file, percentage ) {
            var $li = $( '#'+file.id ),
                $percent = $li.find('.progress .progress-bar');

            // 避免重复创建
            if ( !$percent.length ) {
                $percent = $('<div class="progress progress-striped active">' +
                    '<div class="progress-bar" role="progressbar" style="width: 0%">' +
                    '</div>' +
                    '</div>').appendTo( $li ).find('.progress-bar');
            }

            $li.find('p.state').text('上传中');

            $percent.css( 'width', percentage * 100 + '%' );
        });
        uploader.on( 'uploadSuccess', function( file,response ) {
//            alert(1);
            $( '#'+file.id ).find('p.state').text('已上传');
        });
        uploader.on( 'uploadError', function( file ) {
            $( '#'+file.id ).find('p.state').text('上传出错');
        });
        uploader.on( 'uploadComplete', function( file ) {
            $( '#'+file.id ).find('.progress').fadeOut();
        });
}



